/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package apresentacao;


import java.awt.Toolkit;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import static logica.DisciplinaBO.verificaDisciplina;
import logica.DisciplinaInvalidaException;
import principal.CadeiasCriticas;

/**
 *
 * @author Diego
 */
public class InterfaceInicial extends javax.swing.JPanel {
    private DefaultListModel lista;
    private final int CONTINUA = 0;
    //private DefaultListModel lista;

    /**
     * Creates new form Int
     */
    public InterfaceInicial() {
        lista = new DefaultListModel();
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        botaoAdicionar = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        listaPainel = new javax.swing.JList(lista);
        anoDoCatalogo = new javax.swing.JComboBox();
        botaoNovoAno = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        botaoDeletar = new javax.swing.JButton();
        botaoConsultar = new javax.swing.JButton();
        siglaDisciplina = new JTextField();

        jLabel1.setBackground(java.awt.Color.white);
        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(0, 51, 51));
        jLabel1.setText("Código Disciplina");

        jLabel2.setBackground(java.awt.Color.white);
        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabel2.setText("Selecione um ano e insira as disciplinas que deseja Consultar");

        botaoAdicionar.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        botaoAdicionar.setForeground(new java.awt.Color(0, 51, 51));
        botaoAdicionar.setText("Adicionar");
        botaoAdicionar.setEnabled(false);
        botaoAdicionar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoAdicionarActionPerformed(evt);
            }
        });

        listaPainel.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_INTERVAL_SELECTION);
        jScrollPane1.setViewportView(listaPainel);

        anoDoCatalogo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "2014", "2013", "2012", "2011", "2010", "2009", "2008", "2007", "2006", "2005", "2004", "2003", "2002", "2001", "2000", "1999", "1998" }));
        anoDoCatalogo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                anoDoCatalogoActionPerformed(evt);
            }
        });

        botaoNovoAno.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        botaoNovoAno.setForeground(new java.awt.Color(0, 51, 51));
        botaoNovoAno.setText("Novo ano");
        botaoNovoAno.setEnabled(false);
        botaoNovoAno.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoNovoAnoActionPerformed(evt);
            }
        });

        jLabel3.setBackground(java.awt.Color.white);
        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel3.setForeground(new java.awt.Color(0, 51, 51));
        jLabel3.setText("Ano do Catálogo");

        botaoDeletar.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        botaoDeletar.setForeground(new java.awt.Color(0, 51, 51));
        botaoDeletar.setText("Deletar");
        botaoDeletar.setEnabled(false);
        botaoDeletar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoDeletarActionPerformed(evt);
            }
        });

        botaoConsultar.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        botaoConsultar.setForeground(new java.awt.Color(0, 51, 51));
        botaoConsultar.setText("Consultar");
        botaoConsultar.setEnabled(false);
        botaoConsultar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoConsultarActionPerformed(evt);
            }
        });

        siglaDisciplina.setEnabled(false);
        siglaDisciplina.getText();
        siglaDisciplina.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                siglaDisciplinaActionPerformed(evt);
            }
        });
        siglaDisciplina.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                siglaDisciplinaKeyPressed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(3, 3, 3)
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(anoDoCatalogo, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(3, 3, 3)
                                .addComponent(jScrollPane1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(siglaDisciplina, javax.swing.GroupLayout.PREFERRED_SIZE, 132, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(botaoAdicionar, javax.swing.GroupLayout.PREFERRED_SIZE, 119, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(19, 19, 19)))
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(botaoConsultar, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 117, Short.MAX_VALUE)
                            .addComponent(botaoNovoAno, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(botaoDeletar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(anoDoCatalogo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(botaoDeletar, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(botaoNovoAno, javax.swing.GroupLayout.DEFAULT_SIZE, 52, Short.MAX_VALUE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(siglaDisciplina, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(botaoConsultar, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(botaoAdicionar, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents
/**
 * Método do evento do botaoConsultar
 * Chama o método responsável por apresentar as cadeias das disciplinas
 * @param evt 
 */
    private void botaoAdicionarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoAdicionarActionPerformed
        siglaDisciplinaActionPerformed(evt);
    }//GEN-LAST:event_botaoAdicionarActionPerformed
/**
 * Método do evento do TextField SiglaDisciplina
 * Adiciona uma disciplina na lista caso ela seja válida.
 * @param evt 
 * @see addDisciplina
 */
    private void anoDoCatalogoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_anoDoCatalogoActionPerformed
        anoDoCatalogo.setEnabled(false);
        botaoNovoAno.setEnabled(true);
        siglaDisciplina.setEnabled(true);
    }//GEN-LAST:event_anoDoCatalogoActionPerformed
/**
 * Método do evento do botaoNovoAno
 * Caso haja confirmação do usuário, reseta a interface.
 * Deleta todas as disciplinas, habilita seleção de um novo ano
 * e desabilita todos os outros botoes na Interface.
 * @param evt 
 */
    private void botaoNovoAnoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoNovoAnoActionPerformed
        // TODO add your handling code here:
        int showConfirmDialog = JOptionPane.showConfirmDialog(null, "Todas as disciplinas serão deletadas ao "
            + "selecionar um novo ano\n"+"Deseja continuar?");
        if(showConfirmDialog == CONTINUA){
            while(!lista.isEmpty())
            botaoDeletarActionPerformed(evt);
            siglaDisciplina.setEnabled(false);
            anoDoCatalogo.setEnabled(true);
            botaoNovoAno.setEnabled(false);
        }
    }//GEN-LAST:event_botaoNovoAnoActionPerformed

    private void botaoDeletarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoDeletarActionPerformed
        lista.remove(listaPainel.getSelectedIndex());
        selectDisciplina(lista.getSize()-1);
        habilitaDeletarConsultar();
    }//GEN-LAST:event_botaoDeletarActionPerformed

   /**Metodo responsável pela acao do botao consultar
    * Chama a outra interface. 
    * @param evt - Clique no botao Consultar
    */
    private void botaoConsultarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoConsultarActionPerformed
        botaoConsultar.setEnabled(false);
        botaoDeletar.setEnabled(false);
        referencia.consulta(lista);
        this.setVisible(false);
    }//GEN-LAST:event_botaoConsultarActionPerformed
/**
 * Adiciona uma disciplina no painel se ela for uma disciplina válida
 * @param evt - Digitou Enter no campo texto
 */
    private void siglaDisciplinaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_siglaDisciplinaActionPerformed
        addDisciplina();
    }//GEN-LAST:event_siglaDisciplinaActionPerformed
/**
 * 
 * @param evt 
 */
    private void siglaDisciplinaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_siglaDisciplinaKeyPressed
        botaoAdicionar.setEnabled(true);
    }//GEN-LAST:event_siglaDisciplinaKeyPressed
    
    /**
     * Adiciona uma disciplina no painel se ela for valida
     */
    private void addDisciplina() {
        String codigo= siglaDisciplina.getText().toUpperCase();
        try {
            botaoAdicionar.setEnabled(false);
            verificaSigla(codigo,lista);
        }
        catch(DisciplinaInvalidaException d){
           Toolkit.getDefaultToolkit().beep();
           limpaTextField(siglaDisciplina);
           return;
        }
        limpaTextField(siglaDisciplina);
        lista.addElement(codigo);
        habilitaDeletarConsultar();
        ordenaLista(lista);
    }
    /**
     * Método responsável por habilitar e desabilitar
     * os botoes Deletar e Consultar.
     * Se a variável lista está vazia, são desabilitados.
     * São habilitados caso contrário.
     */
    private void habilitaDeletarConsultar() {  
        if(lista.getSize()==0) {
            this.botaoConsultar.setEnabled(false);
            this.botaoDeletar.setEnabled(false);
        } else {
            this.botaoConsultar.setEnabled(true);
            this.botaoDeletar.setEnabled(true);
        }
    }
     /**
      * Limpa o campo TextField da interface.
      * @param siglaDisciplina 
      */
    private void limpaTextField (JTextField siglaDisciplina) {
        siglaDisciplina.setText("");
    }
    
  /**
   * Seleciona a disciplina de posição n no painel
   * @param n 
   */
    private void selectDisciplina(int n) {
        listaPainel.setSelectedIndex(n);
        listaPainel.ensureIndexIsVisible(n);
    }
    /**
     * Ordena lista por ordem alfabética.
     * Utiliza o algoritmo BubbleSort para a ordenação.
     * A última disciplina adicionada é a selecionada
     * no painel de exibição da variável listaPainel.
     * @param lista 
     * @see selectDisciplina
     */
    private void ordenaLista(DefaultListModel lista) {
        String disciplina1,disciplina2,disciplinaAdd;
        disciplinaAdd = (String) lista.get(lista.getSize()-1);
        //BubleSort
        for(int i=0;i<lista.getSize();i++) {
            for(int j=0;j<lista.getSize()-1;j++) {
                disciplina1=(String) lista.get(j);
                disciplina2=(String) lista.get(j+1);
                if(disciplina1.compareTo(disciplina2)>0) {
                    lista.add(j,disciplina2);
                    lista.remove(j+2);
                }
            }
        }
        //Seleciona ultima disciplina Adicionada
        int index=0;
        for(int i=0;i<lista.getSize();i++){
            disciplina1=(String) lista.get(i);
            if(disciplina1.compareTo(disciplinaAdd)==0) {
                index=i;
                break;
            }
        }
        selectDisciplina(index);
    }
     /**
      * Método que verifica se a disciplina de String S é valida e
      * se está contida na variável lista.
      * Caso não seja válida lança uma exceção do tipo DisciplinaInvalidaException
      * exibindo em um JOptionPane a mensagem de erro.
      * @param s
      * @param lista
      * @throws DisciplinaInvalidaException 
      * @see DisciplinaInvalidaException
      */
    private void verificaSigla(String s,DefaultListModel lista) throws DisciplinaInvalidaException{
        if(s.length() != 5)
           throw new DisciplinaInvalidaException(DisciplinaInvalidaException.TAMANHO_INVALIDO);
            
        String sigla = s.substring(0, 2);
        String numero = s.substring(2, 5);
        String fisica = "F ";
        String padraoLetras = "[A-Z]*[a-z]*";
        String padraoNumeros = "[0-9]*";
           
        if((s.length() != 5) || (s.length() == 0))
            throw new DisciplinaInvalidaException(DisciplinaInvalidaException.LETRAS_INVALIDAS);
        if(!sigla.matches(padraoLetras) && !fisica.matches(sigla.toUpperCase())) 
            throw new DisciplinaInvalidaException(DisciplinaInvalidaException.LETRAS_INVALIDAS);
        if (!numero.matches(padraoNumeros))
            throw new DisciplinaInvalidaException(DisciplinaInvalidaException.NUMERO_INVALIDO);
        if (!verificaDisciplina(s))
            throw new DisciplinaInvalidaException(DisciplinaInvalidaException.DISCIPLINA_INEXISTENTE);
        if(lista.contains(s))
            throw new DisciplinaInvalidaException(DisciplinaInvalidaException.DISCIPLINA_REPETIDA);

    }
    
    public void limpaLista(){
        lista.clear();
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(InterfaceInicial.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(InterfaceInicial.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(InterfaceInicial.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(InterfaceInicial.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new InterfaceInicial().setVisible(true);
            }
        });
    }

    public void setReferenciaProjeto(CadeiasCriticas cc){
        referencia = cc;
    }

    private CadeiasCriticas referencia;
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox anoDoCatalogo;
    private javax.swing.JButton botaoAdicionar;
    private javax.swing.JButton botaoConsultar;
    private javax.swing.JButton botaoDeletar;
    private javax.swing.JButton botaoNovoAno;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JList listaPainel;
    private javax.swing.JTextField siglaDisciplina;
    // End of variables declaration//GEN-END:variables
}
